import random
from time import sleep

from appium.webdriver.common.appiumby import AppiumBy
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.common.by import By

from base.basepage import BasePage


# 首页
class MainPage(BasePage):

    # 本机号码一键登录 或者 不登录跳过
    def login_or_skip(self, is_login):
        if is_login:
            rl_agree_check = (By.ID, "rl_agree_check")
            auth_sdk_checkbox_view = (By.ID, "authsdk_checkbox_view")
            auth_sdk_login_view = (By.ID, "authsdk_login_view")
            if self.find_click(rl_agree_check):
                self.find_click(auth_sdk_checkbox_view)
                self.find_click(auth_sdk_login_view)
                print("本机号码一键登录")
            else:
                print("未弹出一键登录页面")
        else:
            self.back()
            print("跳过一键登录")

    # 点击首页tab
    def click_tab(self, tab_index):
        if tab_index > 4:
            print("首页无此tab")
            return False
        print("点击首页第 %s 个tab" % tab_index)
        self.driver.find_elements(By.ID, "ll_tab_container")[tab_index].click()
        return True

    def quotation_update_for_qihuo(self):
        """
        期货行情更新
        """
        # 行情列表第一次加载时是否更新成功的判断：没有出现加载框或者加载框在设置的时间内消失
        # 超时时长应等于加载框参考出现时长
        if not self.wait_until_visible(3, (By.ID, "cus_loading")):
            print("行情列表第一次加载时更新成功，无加载框")
            is_first_update = True
        else:
            # 超时时长应等于行情正常更新的参考超时时长
            if not self.wait_until_invisible(60, (By.ID, "cus_loading")):
                print("行情列表第一次加载时更新失败")
            else:
                print("行情列表第一次加载时更新成功，有加载框")
                is_first_update = True

            # step4.2.2
            # 行情列表加载成功后，数据是否更新成功的判断：
            # 监视行情列表成交量的变化；成交量变化时，断言行情更新成功，否则超时，断言行情更新失败
        if is_first_update:
            self.wait_until_visible(3, (By.ID, "tv_dealCount"))
            wait_count = 10
            tv_deal_count_text_old = self.find_eles_and_ind_then_gettext(AppiumBy.ID, "tv_dealCount", 0)
            print("tv_deal_count_text_old is", tv_deal_count_text_old)
            is_second_update = False
            while wait_count > 0:
                wait_count = wait_count - 1
                sleep(3)
                tv_deal_count_text_new = self.find_eles_and_ind_then_gettext(By.ID, "tv_dealCount", 0)
                print("tv_deal_count_text_new is", tv_deal_count_text_new)
                if tv_deal_count_text_new != tv_deal_count_text_old:
                    is_second_update = True
                    break
            print("行情列表第二次%s" % ("更新成功" if is_second_update else "未更新"))

    def quotation_update_for_qiquan(self):
        """
        # 监视期权价格的变化；期权价格变化时，断言期权价格更新成功，否则超时，断言期权价格更新失败
        """
        try:
            self.wait_until_invisible(1, (By.ID, "tv_dealCount"))
            wait_count = 10
            tvDealCountTextOld = self.driver.find_element(By.ID, "tv_dealCount").text
            print("tvDealCountTextOld is", tvDealCountTextOld)
            isSecondUpdate = False
            while wait_count > 0:
                wait_count = wait_count - 1
                sleep(1)
                tvDealCountTextNew = self.driver.find_element(By.ID, "tv_dealCount").text
                print("tvDealCountTextNew is", tvDealCountTextNew)
                if tvDealCountTextNew != tvDealCountTextOld:
                    isSecondUpdate = True
                    break
            print("行情列表第二次%s" % ("更新成功" if isSecondUpdate else "未更新"))

        except TimeoutException as e:
            print("TimeoutException.msg", e.msg)

    # 获取自选列表数据
    def get_option_list(self):
        # 回到首页
        self.back_main_activity()
        # 点击自选tab
        self.click_tab(tab_index=1)
        # 如果有同步自选的弹窗，点击同步按钮
        is_find = self.find_click((By.ID, "btn_positive"))
        if is_find:
            # 等待同步  todo 网络数据获取等待时间全局变量配置
            sleep(2)
        # 滚动到顶部
        scroll_to_beginning = 'new UiScrollable(new UiSelector().scrollable(true).instance(1)).scrollToBeginning(10)'
        self.driver.find_elements(AppiumBy.ANDROID_UIAUTOMATOR, scroll_to_beginning)
        option_list = []
        is_not_bottom = True
        # 没有滑动到底部，循环获取自选合约
        while is_not_bottom:
            # 获取合约名称
            options = self.driver.find_elements(By.ID, "tv_option_name")
            # 无自选，直接返回
            if len(options) == 0:
                return options
            # 有自选，依次添加到列表中
            for index in range(len(options)):
                option_name = options[index].text
                # 滑动一屏数据，存在上一页的合约，认为滑动到底部
                if option_name in option_list:
                    is_not_bottom = False
                else:
                    option_list.append(option_name)

            # 滑动一页列表，根据页面最后一个元素，第一个元素的像素 上滑
            top_bounds = options[0].get_attribute("bounds")
            bottom_bounds = options[-1].get_attribute("bounds")
            # ['29', '592', '310', '656', '']
            top_bounds_arr = top_bounds.replace("[", "").replace("]", ",").split(",")
            # ['29', '2077', '310', '2135', '']
            bottom_bounds_arr = bottom_bounds.replace("[", "").replace("]", ",").split(",")
            item_height = int(top_bounds_arr[3]) - int(top_bounds_arr[1])
            self.driver.swipe(bottom_bounds_arr[0], bottom_bounds_arr[1],
                              top_bounds_arr[0], str(int(top_bounds_arr[1]) - item_height), 300)

        print("自选列表--option_list-->>", str(option_list))
        return option_list

    # 选择 国内期现 - 主力合约
    def select_mian_contract(self):
        # 点击行情tab
        self.click_tab(tab_index=2)
        # 点击导航遮罩
        self.click_mask()
        # 点击标题进入行情分类
        self.driver.find_element(By.ID, "title_frg_infomation").click()
        sleep(1)
        # 国内期现（点击展开/收起 分类）
        loc = "//*[@resource-id='cn.com.dfitc.smartinfo:id/rcy_slide']/android.widget.LinearLayout"
        item = self.driver.find_elements(By.XPATH, loc)[0]
        # 国内期现下的分类
        main_list = item.find_elements(By.ID, "rcy_child_slide")
        # 未展开分类，点击展开，再选择主力合约
        if not main_list:
            item.click()
            sleep(1)

        self.driver.find_elements(By.XPATH, "//*[@text='主力合约']")[0].click()
        sleep(1)

    # 行情列表页面，随机选一个行情，加入/删除自选
    def random_select_quot(self):
        # 获取行情列表页面所有行情，随机选择一个行情，点击进入详情
        quotations = self.driver.find_elements(By.ID, "ll_item")
        quotation = random.choice(quotations)
        quotation.click()
        # 获取行情标题
        top_name = self.driver.find_elements(By.ID, "tv_name_top")[0].text
        # 点击"更多"
        self.driver.find_elements(By.ID, "ll_bottom_more")[0].click()
        # 加自选/删自选
        add_or_delete = self.driver.find_elements(By.ID, "tv_add_2_optional")[0].text
        print(top_name + "----点击----" + add_or_delete)
        self.driver.find_elements(By.ID, "ll_add_to_optional_extra")[0].click()
        is_add = add_or_delete == "加自选"
        return is_add, top_name

    # 获取首页轮播图个数
    def get_banner_count(self):
        # 回到首页
        self.back_main_activity()
        # 点击首页tab
        self.click_tab(tab_index=0)
        cycle_indicator = self.driver.find_element(By.ID, "cycle_indicator")
        return len(cycle_indicator.find_elements(By.CLASS_NAME, "android.widget.ImageView"))

    # 点击数据报表
    # index  0-资金流向  1-持仓排名  2-席位分析  3-期市速递  4-仓单日报  5-交割信息  6-极值筛选
    def click_report_forms(self, index):
        if index > 6:
            print("无此数据报表")
            return False
        # 回到首页
        self.back_main_activity()
        # 点击首页tab
        self.click_tab(tab_index=0)
        # 数据报表rv
        if not self.driver.find_elements(By.ID, "recyclerview_main_data_center"):
            # 首次进入，找不到数据报表，进行滑动
            self.swipe_no_release(20, 2000, 20, 250)
            self.driver.tap([(0, 0)])
            # 屏幕录制- 划出数据报表
            # actions = ActionChains(self.driver)
            # actions.w3c_actions = ActionBuilder(self.driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
            # actions.w3c_actions.pointer_action.move_to_location(20, 1996)
            # actions.w3c_actions.pointer_action.pointer_down()
            # actions.w3c_actions.pointer_action.move_to_location(20, 251)
            # actions.w3c_actions.pointer_action.release()
            # actions.perform()
        rv = self.driver.find_elements(By.ID, "recyclerview_main_data_center")[0]
        # 点击某个数据报表
        rv.find_elements(By.ID, "ll_data_report")[index].click()
        self.sleep(2)
        # 断言进入Webview页面
        self.assertIn("AdvWebviewActivity", self.driver.current_activity)
        return True
